package stone926.mods.more_enchantments.mixins;

import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.effect.StatusEffectCategory;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.item.ItemStack;
import net.minecraft.item.MilkBucketItem;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import stone926.mods.more_enchantments.MoreEnchantmentsMod;
import stone926.mods.more_enchantments.enchantments.LargeCapacityEnchantment;
import stone926.mods.more_enchantments.util.RandomUtil;

import java.util.Collection;
import java.util.List;

@Mixin(MilkBucketItem.class)
public class MilkBucketItemMixin {

  @Redirect(method = "finishUsing", at = @At(value = "INVOKE", target = "Lnet/minecraft/item/ItemStack;decrement(I)V"))
  private void handleLargeCapacityEnchantment(ItemStack stack, int amount, ItemStack _stack, World world, LivingEntity user) {
    int lvl = EnchantmentHelper.getLevel(MoreEnchantmentsMod.LARGE_CAPACITY, stack);
    if (lvl > 0) {
      RandomUtil.runIfPossible(LargeCapacityEnchantment.getDecrementChance(lvl), user.getRandom(), () -> stack.decrement(amount));
    } else {
      stack.decrement(amount);
    }
  }

  @Redirect(method = "finishUsing", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/LivingEntity;clearStatusEffects()Z"))
  private boolean handleAntidoteEnchantment(LivingEntity drinker, ItemStack stack, World world) {
    int lvl = EnchantmentHelper.getLevel(MoreEnchantmentsMod.ANTIDOTE, stack);
    if (lvl > 0) {
      Collection<StatusEffectInstance> statusEffects = drinker.getStatusEffects();
      if (!statusEffects.isEmpty()) {
        List<StatusEffectInstance> list = statusEffects
          .stream()
          .filter((effect -> effect.getEffectType().getCategory() == StatusEffectCategory.HARMFUL)).toList();
        for (StatusEffectInstance effect : list) {
          drinker.removeStatusEffect(effect.getEffectType());
        }
      }
      drinker.setFireTicks(0);
      return true;
    } else return drinker.clearStatusEffects();
  }

}
